<template>
  <ych-modal
    :fullscreen="dialogSize === 'full'"
    :size="dialogSize === 'default' ? 'middle' : dialogSize"
    :title="title"
    :visible="visible"
    :destroyOnClose="true"
    @cancel="handleCancel">
    <a-upload-dragger
      name="file"
      :headers="tokenHeader"
      :multiple="false"
      :showUploadList="false"
      :action="importXlsUrl + '&boKey=' + objectCode"
      @change="handleImportXls"
    >
      <p class="ant-upload-drag-icon">
        <a-icon type="inbox"/>
      </p>
      <p class="ant-upload-text">
        {{ $t('m.eform.formDesign.label.dian-ji-huo-tuo-zhuai-wen-jian-dao-ru') }} </p>
      <p class="ant-upload-hint">
        {{ $t('m.eform.formDesign.label.import_button_tip') }} </p>
    </a-upload-dragger>

    <template slot="footer">
      <a-button type="primary" key="file-excel" @click="handleExportTemplate">{{ $t('m.eform.formDesign.label.xia-zai-dao-ru-mo-ban') }}</a-button>
      <a-button key="close" @click="handleCancel">{{ $t('m.common.button.close') }}</a-button>
    </template>
  </ych-modal>
</template>

<script>

  import {downFile} from '@/api/manage'
  import YchConstant from "@/api/YchConstant";
  import {handleCreateFunc, handleExecFunc} from '@/utils/actions'
  import TokenStorageUtil from "../../../utils/TokenStorageUtil";

  export default {
    name: 'ImportDialog',
    components: {},
    props: {
      viewCode: String,
      viewName: String
    },
    data() {
      return {
        title: this.$t('m.common.button.import'),
        visible: false,
        objectCode: null,
        afterScript:null,
        tokenHeader: {'X-Access-Token': TokenStorageUtil.get()},
        url: {
          importXlsUrl: YchConstant.PREFIX_EFORM + '/engine/viewEngine/importXls',
          exportTemplateUrl: YchConstant.PREFIX_EFORM + '/engine/viewEngine/exportTemplate'
        },
        dialogSize: 'default'
      }
    },
    computed: {
      importXlsUrl: function () {
        return `${bootConfig[process.env.NODE_ENV].VUE_APP_API}${this.url.importXlsUrl}?viewCode=` + this.viewCode
      }
    },
    methods: {
      handleCancel() {
        this.visible = false
      },
      handleImportXls(info) {
        if (info.file.status !== 'uploading') {
          //console.log(info.file, info.fileList)
        }
        if (info.file.status === 'done') {
          if (info.file.response.success) {
            // this.messageUtil.success(`${info.file.name} 文件上传成功`);
            if (info.file.response.code === 201) {
              let {message, result: {msg, fileUrl, fileName}} = info.file.response
              let href = bootConfig[process.env.NODE_ENV].VUE_APP_API + fileUrl
              this.$warning({
                  title: message,
                  content: (
                    < div >
                    < span > {msg} < /span><br/ >
                    < span > {this.$t('m.eform.formDesign.label.ju-ti-xiang-qing-qing')} < a href = {href} target = '_blank' download = {fileName} > { this.$t('m.eform.formDesign.label.dian-ji-xia-zai') } < /a></span >
                < /div>
              )
            })
            } else {
              this.messageUtil.success(info.file.response.message || `${info.file.name} `+this.$t('m.common.tip.file_upload_sucess') )
            }
            this.$emit("loadData")
            this.handleCancel();
          } else {
            this.messageUtil.error(`${info.file.name} ${info.file.response.message}.`)
          }

          if (this.afterScript) {
            const func = handleCreateFunc(this.afterScript, this)
            handleExecFunc(func, { info })
          }
        } else if (info.file.status === 'error') {
          this.messageUtil.error(this.$t('m.common.tip.file_upload_error') +`: ${info.file.msg} `)
        }
      },
      handleExportTemplate() {
        const fileName = this.viewName + this.$t('m.eform.formDesign.label.dao-ru-mo-ban')

        downFile(this.url.exportTemplateUrl + '?viewCode=' + this.viewCode, {}, "POST").then((data) => {
          if (!data) {
            this.messageUtil.warning(this.$t('m.eform.formDesign.label.wen-jian-xia-zai-shi-bai'))
            return
          }
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data], {type: 'application/vnd.ms-excel'}), fileName + '.xls')
          } else {
            let url = window.URL.createObjectURL(new Blob([data], {type: 'application/vnd.ms-excel'}))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', fileName + '.xls')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link) //下载完成移除元素
            window.URL.revokeObjectURL(url) //释放掉blob对象
          }
        })
      }
    },
  }
</script>


